<template>
  <el-container>
    <el-main>
      <el-form ref="orderForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="memberId">
              <el-select style="width: 100%;" v-model="memberName" :filter-method="remoteMethod" value-key="id"
                         filterable placeholder="请选择"
                         @change="selectMember">
                <el-option
                  style="width: 600px;"
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                  <div style="display: flex">
                    <span style="width: 60px;">{{item.code}}</span>
                    <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{ item.mobile }}</span>
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                    </div>
                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toSearchMember">搜索客户</div>
                  <div class="elOption1" @click="toAddMember">新增客户</div>

                </div>
                <div style="height: 30px"></div>
                <!--                <el-option style="background-color: #409EFF;text-align: center;" key="-" label="底部隐藏块"-->
                <!--                           value="-"></el-option>-->
                <!--                <el-option class="options" :style="optionHeight"  key="#" label="-&#45;&#45; 新增客户 -&#45;&#45;"-->
                <!--                           value="#"></el-option>-->
                <!--                <el-option style="background-color: #909399;color:white ;text-align: center;position: absolute;bottom:0;width: 100%" key="/" label="-&#45;&#45; 搜索客户 -&#45;&#45;"-->
                <!--                           value="/"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门">
              <el-input v-model="officeName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="5">-->
          <!--            <el-form-item label="销售门店">-->
          <!--              <el-select style="width: 100%" v-model="shopName" value-key="id" @change="changeShop" placeholder="请选择状态" filterable :filter-method="shopMethod">-->
          <!--                <el-option v-for="item in shops"  :key="item.id" :label="item.name" :value="item"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="6">
            <el-form-item label="订货方式">
              <el-select style="width: 100%" v-model="form.orderMethod" placeholder="请选择状态">
                <!--                <el-option label="线上订单" value="0"></el-option>-->
                <el-option label="人工报单" value="1"></el-option>
                <!--                <el-option label="门店销信" value="2"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开票类型">
              <el-select style="width: 100%" v-model="form.taxType" placeholder="请选择状态">
                <el-option label="不开票" value="0"></el-option>
                <el-option label="增票" value="1"></el-option>
                <el-option label="普票" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售人员">
              <el-select style="width: 100%" v-model="operatorName" filterable placeholder="请选择"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="11">
            <el-form-item label="收货地址" prop="address">
              <el-select style="width: 100%" v-model="form.address" value-key="id" filterable placeholder="请选择"
                         @change="selectReceiver">
                <el-option
                  v-for="item in receiverForm"
                  :key="item.id"
                  :label="item.address"
                  :value="item">
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="*" label="底部隐藏块"
                           value="*"></el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;position: absolute;bottom:0;width: 100%"
                           key="#" label="--- 新增收货地址 ---"
                           value="#"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone"/>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="收货人" prop="consignee">
              <el-input v-model="form.consignee"/>
            </el-form-item>
          </el-col>

        </el-row>

        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">销售明细</span>
          <div style="display: flex;padding-top: 10px;padding-bottom: 10px">
            <el-input v-model="query.sn" v-show="form.memberId !=''" placeholder="请输入货号"
                      @change="queryClick"></el-input>
            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"
                       v-show="form.memberId !=''"
                       @click="moreProductClick">添加商品
            </el-button>
          </div>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名">
            <template slot-scope="{row}">
              <el-select style="width: 100%" v-model="row.name" filterable placeholder="请选择" @change="selectClick"
                         :filter-method="productMethod" @focus="tableClick(row)">
                <el-option
                  v-for="(item,index) in listForm"
                  :key="index"
                  style="width:650px"
                  :label="item.name"
                  :value="index"
                >
                  <div style="display: flex">
                    <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                    <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
<!--                    <span style="float: right; color: #8492a6; font-size: 8px;width: 40px;margin-left: 10px">{{ item.price }}</span>-->
                    <div style="width: 200px;">
                      <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                    </div>

                  </div>
                </el-option>
                <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                  <div class="elOption" @click="toAddProduct">搜索商品</div>
                  <div class="elOption1" @click="toSearchProduct">新增商品</div>
                </div>
                <div style="height: 30px"></div>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            max-width="300"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="center"
            width="70">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.quantity"/>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            width="120">
            <template slot-scope="scope">
              <el-input @change="refreshClick" v-model="scope.row.price"></el-input>
              <i @click="isShowHistory(scope)" class="el-icon-arrow-down"
                 style="position: absolute;top:20px;right: 20px"></i>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="120"
            align="right"
            prop="subTotal"
          >
          </el-table-column>


          <el-table-column
            align="center"
            width="70"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a @click="delProduct(row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div
          style="background-color: #EBEEF5;width: 100%;border-left: 1px solid #DCDFE6;border-right: 1px solid #DCDFE6;border-bottom: 1px solid #DCDFE6;display: flex;justify-content: space-between;padding: 10px;">
          <div style="display: flex;flex-direction: column">
            <div style="display:flex;align-items: center;margin-bottom: 10px;margin-left: 10px">
              <div style="display: flex;margin-right: 20px;align-items: center">
                <span style="font-size: 16px;color: #606266">店铺优惠：</span>
                <div style="width: 100px">
                  <span style="font-size: 16px;color: #606266">{{discount}}</span>
                </div>
              </div>
              <div style="display: flex;margin-right: 20px;align-items: center">
                <span style="font-size: 16px;color: #606266">运费金额：</span>
                <div style="width: 100px">
                  <span style="font-size: 16px;color: #606266">{{form.freight}}</span>
                </div>
              </div>
              <div style="display: flex;align-items: center;justify-content: space-between">
                <span style="font-size: 16px;color: red">合计预收：{{amount}}</span>
              </div>
            </div>
            <div style="display: flex">
              <el-form-item label="配送方式" style="width: 250px">
                <el-select style="width:100%" v-model="form.shippingMethod" @change="changgeShipping" placeholder="请选择配送方式">
                  <el-option v-if="shippings.length>0" v-for="item in shippings" :label="item|watchShipping"
                             :value="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发货仓库" style="width: 250px"  v-if="form.shippingMethod!=''">
                <el-select value-key="id" v-model="sendFormShopName" filterable placeholder="请选择" @change="selectShop">
                  <el-option
                    v-for="item in shopList"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="送货员" style="margin-left: 10px;" v-if="form.shippingMethod==2">
                <el-select style="width: 100%" v-model="sendOperatorName" value-key="id" filterable placeholder="请选择"
                           @change="selectSysSendEmployee">
                  <el-option
                    v-for="item in sysEmployeeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>

            <el-form-item label="买家留言" style="width: 550px">
              <el-input v-model="form.memo"/>
            </el-form-item>
            <!--            <div style="display: flex;align-items: center;justify-content: space-between">-->
            <!--              <div style="display: flex;margin-right: 20px;align-items: center">-->
            <!--                <span style="font-size: 16px;color: #606266">抹零金额：</span>-->
            <!--                <div style="width: 100px">-->
            <!--                  <el-input v-model="form.offsetAmount " @change="toCalculateClick"/>-->
            <!--                </div>-->
            <!--              </div>-->
            <!--            </div>-->
          </div>
          <div style="position: relative">

            <div style="margin-bottom: 10px">
              <span style="font-size: 16px;color: rgba(26, 26, 30, 1);font-weight: 400;">支付方式</span>
            </div>
            <div style="margin-bottom: 10px;display: flex;justify-content: space-between;align-items: center;"
                 v-for="(item,index) in form.paymentVo">
              <div>
                <span style="font-size: 14px;font-weight: 400;color: rgba(26, 26, 30, 1);display: block">{{item.paymentPluginName}}</span>
                <span
                  style="font-size: 12px;font-weight: 400;color: rgba(231, 91, 83, 1);line-height: 18px; display: block; margin-top: 5px;">可抵扣余额¥{{item.balance}}</span>
              </div>
              <el-switch
                style="display: block"
                v-model="item.chk"
                active-color="#13ce66"
                @change="chooseClick(index,item.chk)"
                inactive-color="#ff4949">
              </el-switch>
            </div>
            <div style="display: flex;align-items: center;margin-bottom:10px;position: relative"
                 v-for="(item,index) in pay">
              <!--              <el-button style="position: absolute;left: -140px;" type="primary"-->
              <!--                         v-show="index+1 == pay.length && pay.length<3" @click="addPayClick(index)">添加支付方式-->
              <!--              </el-button>-->
              <i style="position: absolute;left: -30px;color: #606266;font-size: 22px"
                 v-show="index+1 == pay.length && pay.length<4 && payAmountType == false&&amount!=0"
                 @click="addPayClick(index)"
                 class="el-icon-circle-plus-outline"></i>
              <div style="width: 150px">
                <el-select style="" v-model="item.paymentPluginId" placeholder="请选择状态">
                  <el-option label="现金" value="cashPayPlugin"></el-option>
                  <el-option label="水票" value="paperPayPlugin" v-if="isWaterShow==true"></el-option>
                  <el-option label="转账" value="bankPayPlugin"></el-option>
                  <el-option label="月结" value="debtPayPlugin"></el-option>
                </el-select>
              </div>
              <div style="width: 80px;margin-left: 10px">
                <el-input @blur="inputClick(index)" v-model="item.amount"/>
              </div>
              <i @click="delClick(index)" style="margin-left:10px" class="el-icon-delete" v-show="index !=0"></i>
            </div>
            <span v-if="waitePay!=0" style="color: red;position: relative;bottom:0px;right: 0">剩余应付：{{waitePay}}</span>
          </div>

        </div>
        <!--        <el-button type="primary" style="margin-top: 20px" @click="addProduct">添加规格</el-button>-->
        <el-button type="primary" style="margin-top: 20px" :loading="clicked" @click="saveClick('orderForm')">保存
        </el-button>
        <el-button type="primary" style="margin-top: 20px" :loading="clickSave" @click="saveSend('orderForm')">保存并发货
        </el-button>
      </el-form>
      <el-dialog
        title="新增商品"
        :visible.sync="procuctVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="productClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="新增商品"
        :visible.sync="orderVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="orderClose">
        <div style="position: relative;">
          <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
        </div>
      </el-dialog>
      <el-dialog
        title="新增客户"
        :visible.sync="memberVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="memberClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="queryType"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="queryClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
        </div>
      </el-dialog>
      <el-dialog
        title="新增地址"
        :visible.sync="receiverVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="receiverClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <!--          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>-->
          <receiverAdd :key="times" @orderReceiver="orderReceiver" pathType="0" :memberId="form.memberId"></receiverAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="双击选择客户"
        :visible.sync="memberTableVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="memberTableClose">
        <div style="position: relative;">
          <!--          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>-->
          <member-table :key="times" @memberDouble="memberDouble" @memberTableClose="memberTableClose"></member-table>
        </div>
      </el-dialog>
      <el-dialog
        v-el-drag-dialog
        title="商品近期销售金额"
        :visible.sync="historyType"
        width="600px"
        append-to-body
        :before-close="historyClose"
      >
        <el-table
          :data="historys"
          border
          @row-dblclick="doubleHistory"
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="销售时间"
            max-width="300"
            align="createDate"
          >
            <template slot-scope="{row}">
              <span>{{row.createDate|datetimeFormatter}}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="单价"
            width="120"
            prop="price">
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog
        v-el-drag-dialog
        title="发货"
        :visible.sync="sendType"
        width="60%"
        append-to-body
        :before-close="sendClose"
      >
        <div style="position: relative;">
          <sendList ref="send" :memberMemo="memberMemo" :key="times" :weekType="weekType" :send-form="sendForm"
                    @sendClose="sendClose"/>
          <div style="display: flex;justify-content: flex-end;align-items: center;margin-top: 20px">
            <el-button v-permission="['saleout.add']" type="primary" @click="delivery">发货</el-button>
          </div>
        </div>
      </el-dialog>
      <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    </el-main>
  </el-container>
</template>
<script>
  import {list as shopList} from '@/api/shop'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import sendList from './components/send'
  import memberTable from '@/components/MemberTable/index'
  import {mapGetters} from 'vuex'
  import {EventBus} from '@/api/eventBus'
  import {list as productList} from '@/api/product'
  import {list as memberList} from '@/api/member'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import {
    getMenuTree
  } from '@/api/sysMch.js'
  import { save, calculate, find, list, getHistoryList, last, shipping } from '@/api/order'
  import utils from '../../utils/utils.js'
  import {receiverLocation} from '@/api/mapLine'
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '@/components/ProductList/productList'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import memberAdd from '@/views/member/add'
  import receiverAdd from '@/views/receiver/add'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'
  import {list as receiverList} from '@/api/receiver'
  export default {
    directives: {elDragDialog,permission},
    name: 'order-add',
    data() {
      return {
        receiverId: '',
        sendType: false,
        sendOperatorName:'',
        responseData: {},
        weekDate:[],
        changeIndex: '',
        shopList: [],
        sendFormShopName:'',
        isWaterShow: false,
        addProducts: [],
        callType: '',
        shippings: [],
        historys: [],
        historyList: [],
        memberTableVisible: false,
        clicked: false, // 按钮防双击
        times: null,
        memberOrders: [],
        areaName: '',
        weekType: '',
        shopName: '',
        sendForm: {
          shopId:'',
          shippingEmployeeId:'',
        },
        form: {
          memberId: '',
          taxType: '0',
          receiverId: '',
          shopId: '',
          orderDate: new Date(),
          operatorId: '',
          // property: 0,
          orderMethod: '1',
          shippingMethod: '',
          officeId: '',
          areaId: null,
          areaName: '',
          address: '',
          memo: '',
          consignee: '',
          phone: '',
          freight: 0,
          amountPayable: 0,
          amountPaid: 0,
          paymentMethod: '0',
          subPrice: 0,
          subQuantity: 0,
          offsetAmount: 0,
          pointDiscount: 0,
          cardDiscount: 0,
          paymentVo: []

        },
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        discount: 0,
        historyType: false,
        pageNum: 0,
        waitePay:'',
        shops: [],
        optionHeight: '',
        clickSave: false,
        memberMemo: '',
        memberChose: [],
        listForm: [],
        tableIndex: '',
        productHeight: '',
        procuctVisible: false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        // district: {province: 440000, city: '广州市', area: '海珠区'},
        district: {province: 350000, city: 350200, area: 350203},
        memberName: '',
        memberList: [],
        memberVisible: false,
        memberType: 'add',
        sysEmployeeList: [],
        operatorName: '',
        officeName: '',
        rules: {
          memberId: [
            {required: true, message: '客户名称不能为空', trigger: 'blur'},
          ],

          address: [
            {required: true, message: '收货地址不能为空', trigger: 'blur'}
          ],
        },
        queryType: false,
        findByList: [],
        receiverType: false,
        memberId: '',
        value2: false,
        pay: [
          {
            amount: 0,
            chk: false,
            paymentPluginId: "cashPayPlugin",
            paymentPluginName: "现金"
          }
        ],
        amount: 0,
        receiverForm: [],
        receiverVisible: false,
        payAmountType: false
      }
    },
    created() {
      this.loadMenus()
      this.callType = this.$route.query.type
      console.log(this.$route.query)
      if (this.$route.query.id) {
        this.form.memberId = this.$route.query.id
        this.memberName = this.$route.query.name
        this.loadReceiver()
      }
      this.loadShop('')
      if (this.form.memberId != '') {
        this.loadShipping()
      }
      console.log(this.employee);
      if (this.employee != null) {
        this.form.operatorId = this.employee.id;
        this.form.officeId = this.employee.officeId;
        this.officeName = this.employee.officeName;
        this.operatorName = this.employee.name;
      }
      this.loadlist('');
      this.loadMember('');
      this.loadSysEmployee();

    },
    watch: {
      $route(newName,oldName){
        if (newName!=oldName){
          if (this.$route.query.id) {
            this.form.memberId = this.$route.query.id
            this.memberName = this.$route.query.name
            this.loadReceiver()
            this.loadShipping()
          }
        }
      },
      memberChose(newName, oldName) {
        if (newName.length == 0) {
          this.loadShipping()
        }
      }
    },
    filters: {
      watchShipping(val) {
        if (val == 0) {
          return '普通快递'
        } else if (val == 1) {
          return '到店核销'
        } else if (val == 2) {
          return '同城物流'
        }
      }
    },
    computed: {
      ...mapGetters([
        'employee'
      ])
    },
    components: {
      productAdd, productTable, Distpicker, memberAdd, OfficeDialog, productRadio, receiverAdd, memberTable, sendList
    },
    methods: {
      loadMenus() {

        getMenuTree().then(res => {
          res.data.forEach(list => {
            if (list.permission === 'product.list') {
              const loadWater = list.childrens.find(item => {
                return item.permission === 'waterTicket-list'
              })
              if (loadWater !== undefined) {
                this.isWaterShow = true
              }
            }
          })

        })
      },
      loadMapLine(){
        let params=new URLSearchParams()
        params.append('receiverId',this.form.receiverId)
        receiverLocation(params).then(res=>{
          this.sendFormShopName=res.data.shopName
          this.sendForm.shopId=res.data.mapLine.shopId
          this.sendOperatorName=res.data.shippingEmployeeName
          this.sendForm.shippingEmployeeId=res.data.mapLine.shippingEmployeeId
        })
      },
      selectSysSendEmployee(data){
          this.sendOperatorName=data.name
          this.sendForm.shippingEmployeeId=data.id
      },
      changgeShipping(e){
        if (e==2){
          this.loadMapLine()
        }
      },
      selectShop(data){
        this.sendFormShopName=data.name
        this.sendForm.shopId=data.id
      },
      toSearchMember() {

        // this.memberName = ''
        this.memberTableVisible = true
      },
      memberTableClose() {
        this.memberTableVisible = false
      },
      productMethod(query) {
        this.loadlist(query)
      },
      isShowHistory(data) {

        this.changeIndex = data.$index
        let params = new URLSearchParams()
        params.append('productId', data.row.productId)
        params.append('memberId', this.form.memberId)
        if (data.row.productId){
          getHistoryList(params).then(res => {
            this.historys = res.data
            if (res.data.length > 0) {
              this.historyType = true

            }
          })
        }

      },
      doubleHistory(val) {
        this.productList[this.changeIndex].price = val.price
        this.procuctFilter();
        this.calculateClick();
        this.historyType = false
      },
      // addMemberClick(val){
      //     val.forEach(item=>{
      //       this.form.memberId = item.id;
      //       this.memberName=item.name
      //     })
      //   this.loadReceiver()
      // },
      shopMethod(data) {
        this.loadShop(data)
      },
      historyClose() {
        this.historyType = false
      },
      changeShop(data) {
        this.shopName = data.name
        this.form.shopId = data.id
      },
      memberDouble(data) {
        var _this = this
        _this.resetClick()
        _this.receiverForm = [];
        this.form.memberId = data.id;
        this.memberName = data.name
        this.memberTableVisible = false
        this.loadReceiver()
        this.addProduct()
      },
      loadShop(query) {
        let params = new URLSearchParams()
        params.append('name', query)
        shopList(params).then(res => {
          this.shopList = res.data.data
        })
      },
      //删除商品列表
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }
        if (this.productList.length == 0) {
          this.amount = 0
        }
        this.calculateClick()
      },
      remoteMethod(query) {
        this.loadMember(query)
      },
      loadShipping() {
        var _this = this
        const params = {
          memberId: this.form.memberId,
        }
        if (this.productList.length == 0) {
          this.pageNum += 1
          last(params).then(res => {
            if (res.data != null) {
              if (res.data.itemList.length > 0) {
                res.data.itemList.forEach(item => {
                  if (item.subType == 0 || item.subType == 4) {
                    this.productList.push(item)
                  }
                })
              }
              _this.procuctFilter();
              _this.calculateClick();
            }
          }).catch(error => {
            console.log(error)
          })
        }
      },
      sendClose() {
        this.sendType = false
      },
      //新增商品
      addProduct() {
        // if (this.form.memberId == ''){
        //   this.$message({
        //     message: '请先选择客户',
        //     type: 'warning'
        //   });
        //   return
        // }
        var _this = this
        if (_this.productList.length == 0) {
          _this.productList.push({
            productId: '',
            name: '',
            sn: '',
            price: '',
            orders: '',
            quantity: '',
            subTotal: '',
            amountPaid: 0,
            spec: '',
            discount: 0,
            cost: 0,
            unit: ''
          })
        } else {
          if (_this.productList[_this.productList.length - 1].productId != '') {
            _this.productList.push({
              productId: '',
              name: '',
              sn: '',
              price: '',
              orders: '',
              quantity: '',
              subTotal: '',
              amountPaid: 0,
              spec: '',
              discount: 0,
              cost: 0,
              unit: ''
            })
          }
        }
      },
      //商品总数据
      loadlist(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('keyword', query)
        params.append('sn', _this.keyword.sn)
        productList(params).then(response => {
          console.log(response);
          _this.listForm = response.data.data
          if (_this.listForm.length > 4) {
            this.productHeight = 'height:35px'
          } else {
            this.productHeight = 'height:55px'
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      //更多商品弹出
      moreProductClick() {
        var _this = this;
        if (_this.form.memberId == '') {
          this.$message({
            message: '请先选择客户',
            type: 'warning'
          });
          return
        }
        _this.orderVisible = true;
      },

      doubleClick(data) {
        console.log(data)
        let params = new URLSearchParams()
        params.append('productId', data.id)
        params.append('memberId', this.form.memberId)
        getHistoryList(params).then(res => {
          this.historyList = res.data
          // console.log(this.historyList)
          if (this.historyList.length > 0) {
            var goodsDetails = {
              productId: data.id,
              name: data.name,
              sn: data.sn,
              price: this.historyList[0].price,
              orders: data.orders,
              subTotal: this.historyList[0].price,
              cost: data.cost,
              amountPaid: 0,
              discount: 0,
              quantity: 1,
              spec: data.spec1 + data.spec2,
              unit: data.unit,
            };
            this.productList.push(goodsDetails)
            this.procuctFilter();
            this.calculateClick()
          } else {
            var goodsDetails = {
              productId: data.id,
              name: data.name,
              sn: data.sn,
              price: data.price,
              orders: data.orders,
              subTotal: data.price,
              cost: data.cost,
              amountPaid: 0,
              discount: 0,
              quantity: 1,
              spec: data.spec1 + data.spec2,
              unit: data.unit,
            };
            this.productList.push(goodsDetails)
            this.procuctFilter();
            this.calculateClick()
          }
        })
      },
      addClick(data) {
        var _this = this
        // var index=0
        this.addProducts = data
        console.log(data.length)
        // _this.addProducts=data
        // for (var i=0;i<this.addProducts.length;i++){
        data.forEach((item, index) => {
          let params = new URLSearchParams()
          params.append('productId', item.id)
          params.append('memberId', this.form.memberId)
          getHistoryList(params).then(res => {
            this.historyList = res.data
            if (this.historyList.length > 0) {
              console.log(this.historyList[0].id)
              var goodsDetails = {
                productId: data[index].id,
                name: this.historyList[0].name,
                sn: this.historyList[0].sn,
                price: this.historyList[0].price,
                orders: this.historyList[0].orders,
                subTotal: this.historyList[0].price,
                cost: this.historyList[0].cost,
                amountPaid: 0,
                discount: 0,
                quantity: 1,
                spec: _this.addProducts[index].spec1 + _this.addProducts[index].spec2,
                unit: this.historyList[0].unit
              };
              _this.productList.push(goodsDetails)
              _this.procuctFilter();
              _this.calculateClick();
            } else if (_this.historyList.length == 0) {
              var goods = {
                productId: _this.addProducts[index].id,
                name: _this.addProducts[index].name,
                sn: _this.addProducts[index].sn,
                price: _this.addProducts[index].price,
                orders: _this.addProducts[index].orders,
                subTotal: _this.addProducts[index].price,
                cost: _this.addProducts[index].cost,
                amountPaid: 0,
                discount: 0,
                quantity: 1,
                spec: _this.addProducts[index].spec1 + _this.addProducts[index].spec2,
                unit: _this.addProducts[index].unit
              };
              _this.productList.push(goods)
              _this.procuctFilter();
              _this.calculateClick();
            }
          })
        })

        // }
        this.orderVisible = false;
      },
      orderClose() {
        this.orderVisible = false;
        if (this.productList.length > 0 && this.chooseOrderName != '') {
          this.productList[this.tableIndex].name = this.chooseOrderName
        }
        this.$refs.productList.cancelClick();
      },
      toAddProduct(){
        this.orderVisible = true;

      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      //商品表下拉选择
      selectClick(index) {
        console.log(index)
        var _this = this
        if (index == '#') {
          _this.procuctVisible = true;
        } else if (index == '/') {
          _this.orderVisible = true;
        } else {
          console.log(_this.listForm)
          let params = new URLSearchParams()
          params.append('productId', _this.listForm[index].id)
          params.append('memberId', this.form.memberId)
          getHistoryList(params).then(res => {
            if (res.data.length > 0) {
              var goodsDetails = {
                productId: _this.listForm[index].id,
                name: _this.listForm[index].name,
                sn: _this.listForm[index].sn,
                cost: _this.listForm[index].cost,
                price: res.data[0].price,
                orders: _this.listForm[index].orders,
                subTotal: res.data[0].price,
                unit: _this.listForm[index].unit,
                spec: _this.listForm[index].spec1 + _this.listForm[index].spec2,
                amountPaid: 0,
                discount: 0,
                quantity: 1
              };
              _this.productList[_this.tableIndex] = goodsDetails
              this.procuctFilter();
              this.calculateClick()
            } else {
              var goodsDetails = {
                productId: _this.listForm[index].id,
                name: _this.listForm[index].name,
                sn: _this.listForm[index].sn,
                cost: _this.listForm[index].cost,
                price: _this.listForm[index].price,
                orders: _this.listForm[index].orders,
                subTotal: _this.listForm[index].price,
                unit: _this.listForm[index].unit,
                spec: _this.listForm[index].spec1 + _this.listForm[index].spec2,
                amountPaid: 0,
                discount: 0,
                quantity: 1
              };
              console.log(_this.tableIndex)
              console.log(goodsDetails)
              _this.productList[_this.tableIndex] = goodsDetails
              this.procuctFilter();
              this.calculateClick()
            }
          })
        }
      },
      //获取当前点击商品表行
      tableClick(data) {
        this.tableIndex = this.productList.indexOf(data);
        console.log(this.chooseOrderName)
        setTimeout(() => {
          this.chooseOrderName = this.productList[this.tableIndex].name
        }, 300)

      },
      //新增商品弹窗
      productClose() {
        this.procuctVisible = false;
        this.productList[this.tableIndex].name = this.chooseOrderName
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      //商品过滤
      procuctFilter() {
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          var key = this.productList[i].productId;
          if (temp[key]) {
            temp[key].productId = temp[key].productId;
            temp[key].quantity = temp[key].quantity + this.productList[i].quantity;
            temp[key].subTotal = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
            temp[key].amountPaid = temp[key].subTotal
          } else {
            temp[key] = {};
            temp[key].productId = this.productList[i].productId;
            temp[key].quantity = this.productList[i].quantity;
            temp[key].subTotal = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
            temp[key].amountPaid = temp[key].subTotal
          }
          temp[key].subType = this.productList[i].subType;
          temp[key].name = this.productList[i].name;
          temp[key].sn = this.productList[i].sn;
          temp[key].price = this.productList[i].price;
          temp[key].cost = this.productList[i].cost;
          temp[key].orders = this.productList[i].orders;
          temp[key].discount = this.productList[i].discount;
          temp[key].spec = this.productList[i].spec;
          temp[key].unit = this.productList[i].unit
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
      },
      //订单保存
      saveSend(form){
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            if (_this.pay.length > 1) {
              var cashPayPlugin = [];
              var paperPayPlugin = [];
              var bankPayPlugin = [];
              var debtPayPlugin=[]
              _this.pay.forEach(function (item) {
                if (item.paymentPluginId == 'cashPayPlugin') {
                  cashPayPlugin.push(item)
                } else if (item.paymentPluginId == 'paperPayPlugin') {
                  paperPayPlugin.push(item)
                } else if (item.paymentPluginId == 'bankPayPlugin') {
                  bankPayPlugin.push(item)
                } else if (item.paymentPluginId == 'debtPayPlugin') {
                  debtPayPlugin.push(item)
                }
              })
              if (cashPayPlugin.length > 1 || paperPayPlugin.length > 1 || bankPayPlugin > 1 || debtPayPlugin > 1) {
                _this.$message({
                  message: '请勿选择相同的支付方式',
                  type: 'warning'
                });
                return
              }
            }
            if (_this.pay.length > 0) {
              var item = {}
              _this.pay.forEach(function (item, index) {
                if (item.amount > 0) {
                  if (item.paymentPluginId == 'cashPayPlugin') {
                    item.paymentPluginName = '现金';
                    item.chk = true
                  } else if (item.paymentPluginId == 'paperPayPlugin') {
                    item.paymentPluginName = '纸质水票';
                    item.chk = true
                  } else if (item.paymentPluginId == 'bankPayPlugin') {
                    item.paymentPluginName = '转账';
                    item.chk = true
                  } else if (item.paymentPluginId == 'debtPayPlugin') {
                    item.paymentPluginName = '月结欠款';
                    item.chk = true
                  }
                } else {
                  if (item.paymentPluginId == 'cashPayPlugin') {
                    item.paymentPluginName = '现金';
                    item.chk = false
                  } else if (item.paymentPluginId == 'paperPayPlugin') {
                    item.paymentPluginName = '纸质水票';
                    item.chk = false
                  } else if (item.paymentPluginId == 'bankPayPlugin') {
                    item.paymentPluginName = '转账';
                    item.chk = false
                  } else if (item.paymentPluginId == 'debtPayPlugin') {
                    item.paymentPluginName = '月结欠款';
                    item.chk = false
                  }
                }
              })
            }
            var paymentVo = _this.form.paymentVo.concat(_this.pay);
            let itemList = [];
            _this.productList.forEach(function (item) {
              if (item.productId != '' ){
                var goodsDetails = {
                  productId: item.productId,
                  name: item.name,
                  sn: item.sn,
                  price: item.price,
                  quantity: item.quantity,
                  spec: item.spec,
                  cost: item.cost,
                  unit: item.unit
                };
                itemList.push(goodsDetails)
              }
            });
            let formData = {
              taxType: _this.form.taxType,
              memberId: _this.form.memberId,
              orderDate: _this.form.orderDate,
              operatorId: _this.form.operatorId,
              orderMethod: _this.form.orderMethod,
              shippingMethod: _this.form.shippingMethod,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              receiverId: _this.form.receiverId,
              memo: _this.form.memo,
              shopId: _this.form.shopId,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              freight: _this.form.freight,
              amountPayable: _this.form.amountPayable,
              amountPaid: _this.form.amountPaid,
              // paymentMethod: _this.form.paymentMethod,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              offsetAmount: _this.form.offsetAmount,
              // pointDiscount: _this.form.pointDiscount,
              paymentVo: paymentVo,
              itemList: itemList
            };
            var amount = 0
            paymentVo.forEach(function (item) {
              amount += Number(item.amount)
            })
            if (this.waitePay==0) {
              _this.clickSave = true
              save(formData).then(res => {
                _this.clickSave = false
                _this.responseData = res.data
                EventBus.$emit('call-add', res.data)
                EventBus.$emit('order-add', res.data)
                find(res.data.id).then(response => {
                  // _this.sendForm = response.data
                  response.data.order.itemList.forEach(item => { // 初始化发货数量
                    item.shippedQuantity = item.availableShippedQuantity
                  })
                  this.delivery(res.data.id,response.data.order.itemList)
                  _this.receiverId = response.data.order.receiverId
                  _this.memberMemo = response.data.memberMemo
                  if (!utils.isNull(response.data.order.itemList)) {
                    var packageForm = []
                    response.data.order.itemList.forEach(function (item) {
                      if (item.subType == 1) {
                        packageForm.push(item)
                      }
                    })
                    if (packageForm.length > 0) {
                      _this.weekType = true
                    } else {
                      _this.weekType = false
                    }
                  }
                  // this.sendType = true
                  this.times = new Date().getSeconds()
                }).catch(error => {
                })
                // _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                //   _this.$router.push({
                //     path: '/order/list'
                //   })
                // })// 关闭当前tab回到列表
              }).catch(error => {
                _this.clickSave = false
              })
            } else {
              _this.clickSave = false
              _this.$message({
                message: '请先确认商品是否付完款',
                type: 'warning'
              });
              return
            }

          } else {
            return false
          }
        })
      },

      saveClick(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            if (_this.pay.length > 1) {
              var cashPayPlugin = [];
              var paperPayPlugin = [];
              var bankPayPlugin = [];
              var debtPayPlugin = []
              _this.pay.forEach(function (item) {
                if (item.paymentPluginId == 'cashPayPlugin') {
                  cashPayPlugin.push(item)
                } else if (item.paymentPluginId == 'paperPayPlugin') {
                  paperPayPlugin.push(item)
                } else if (item.paymentPluginId == 'bankPayPlugin') {
                  bankPayPlugin.push(item)
                } else if (item.paymentPluginId == 'debtPayPlugin') {
                  debtPayPlugin.push(item)
                }
              })
              if (cashPayPlugin.length > 1 || paperPayPlugin.length > 1 || bankPayPlugin > 1 || debtPayPlugin > 1) {
                _this.$message({
                  message: '请勿选择相同的支付方式',
                  type: 'warning'
                });
                return
              }
            }
            if (_this.pay.length > 0) {
              var item = {}
              _this.pay.forEach(function (item, index) {
                if (item.amount > 0) {
                  if (item.paymentPluginId == 'cashPayPlugin') {
                    item.paymentPluginName = '现金';
                    item.chk = true
                  } else if (item.paymentPluginId == 'paperPayPlugin') {
                    item.paymentPluginName = '纸质水票';
                    item.chk = true
                  } else if (item.paymentPluginId == 'bankPayPlugin') {
                    item.paymentPluginName = '转账';
                    item.chk = true
                  } else if (item.paymentPluginId == 'debtPayPlugin') {
                    item.paymentPluginName = '月结欠款';
                    item.chk = true
                  }
                } else {
                  if (item.paymentPluginId == 'cashPayPlugin') {
                    item.paymentPluginName = '现金';
                    item.chk = false
                  } else if (item.paymentPluginId == 'paperPayPlugin') {
                    item.paymentPluginName = '纸质水票';
                    item.chk = false
                  } else if (item.paymentPluginId == 'bankPayPlugin') {
                    item.paymentPluginName = '转账';
                    item.chk = false
                  } else if (item.paymentPluginId == 'debtPayPlugin') {
                    item.paymentPluginName = '月结欠款';
                    item.chk = false
                  }
                }
              })
            }
            var paymentVo = _this.form.paymentVo.concat(_this.pay);
            let itemList = [];
            _this.productList.forEach(function (item) {
              if (item.productId != '') {
                var goodsDetails = {
                  productId: item.productId,
                  name: item.name,
                  sn: item.sn,
                  price: item.price,
                  quantity: item.quantity,
                  spec: item.spec,
                  cost: item.cost,
                  unit: item.unit
                };
                itemList.push(goodsDetails)
              }
            });
            let formData = {
              taxType: _this.form.taxType,
              memberId: _this.form.memberId,
              orderDate: _this.form.orderDate,
              operatorId: _this.form.operatorId,
              orderMethod: _this.form.orderMethod,
              receiverId: _this.form.receiverId,
              shippingMethod: _this.form.shippingMethod,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              memo: _this.form.memo,
              shopId: _this.form.shopId,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              freight: _this.form.freight,
              amountPayable: _this.form.amountPayable,
              amountPaid: _this.form.amountPaid,
              // paymentMethod: _this.form.paymentMethod,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              offsetAmount: _this.form.offsetAmount,
              // pointDiscount: _this.form.pointDiscount,
              paymentVo: paymentVo,
              itemList: itemList
            };
            if (this.waitePay==0) {
              _this.clicked = true
              save(formData).then(response => {

                _this.clicked = false

                _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                  _this.$router.push({
                    path: '/order/list'
                  })
                })// 关闭当前tab回到列表

                EventBus.$emit('order-add', response.data)
                EventBus.$emit('call-add', response.data)

              }).catch(error => {
                _this.clicked = false
              })
            }else {
              _this.clicked = false
              _this.$message({
                message: '请先确认商品是否付完款',
                type: 'warning'
              });
              return
            }

          } else {
            return false
          }
        })
      },

      delivery(data,itemList) {

        var _this = this
        var date=new Date();

        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        date= y + '-' + m + '-' + d;

        const params = new URLSearchParams()
        params.append('shopId', _this.sendForm.shopId)

        if (_this.sendForm.shippingEmployeeId!=''){
          params.append('shippingEmployeeId',_this.sendForm.shippingEmployeeId)
        }
        if (_this.form.receiverId!=''){
          params.append('receiverId',_this.form.receiverId)
        }
        console.log(params)
        console.log(date)
        params.append('orderDate',date)
        shipping(data, params, itemList).then(response => {
          console.log(111111111)
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          })
        }).catch(error => {
          console.log('error!!')
        })
        EventBus.$emit('order-add', this.responseData)
        setTimeout(() => {
          _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
            _this.$router.push({
              path: '/order/list'
            })
          })// 关闭当前tab回到列表
        }, 1000)
      },
      //会员选择
      loadMember(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('keyword', query)
        memberList(params).then(response => {
          console.log(response);
          _this.memberList = response.data.data
          if (_this.memberList.length > 4) {
            this.optionHeight = 'height:35px'
          } else {
            this.optionHeight = 'height:55px'
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      toAddMember() {
        this.memberVisible = true;
        this.times = new Date().getSeconds()
      },
      selectMember(data) {
        var _this = this;
        // _this.form.address = '';
        // _this.form.areaName = '';
        // _this.form.areaId = '';
        // _this.form.consignee = '';
        // _this.form.phone = '';
        // _this.productList = []

        if (data == '#') {
          _this.memberVisible = true;
          this.times = new Date().getSeconds()
        } else if (data == '/') {
          _this.memberName = ''
          _this.memberTableVisible = true
        } else {
          _this.resetClick()
          _this.receiverForm = [];
          _this.form.memberId = data.id;
          _this.loadShipping()
          _this.loadReceiver();
          _this.addProduct()
          // if (!utils.isNull(data.areaId)) {
          //   _this.form.address = data.address
          //   _this.form.areaName = data.areaName
          //   _this.form.areaId = data.areaId;
          // }
        }
      }
      ,
      memberClose() {
        this.memberVisible = false;
        this.memberName = '';
      }
      ,
      memberClick(data) {
        var _this = this;
        _this.resetClick()
        _this.memberName = data.name;
        _this.form.memberId = data.id;
        _this.memberVisible = false;
        _this.loadShipping()
        _this.loadReceiver();
        _this.addProduct()
      }
      ,
      //  业务员
      loadSysEmployee() {
        var _this = this
        let params = new URLSearchParams();
        sysEmployeeList(params).then(response => {
          console.log(response);
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      }
      ,
      selectSysEmployee(data) {
        this.form.operatorId = data
      }
      ,
      //  销售公司
      dialogShow() {
        console.log('点击了');
        this.$refs.officeDialog.show()
      }
      ,
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },
      //  计算
      calculateClick() {
        var _this = this;
        let itemList = [];
        console.log(_this.productList)
        _this.productList.forEach(function (item) {
          if (item.productId != '') {
            var goodsDetails = {
              productId: item.productId,
              name: item.name,
              sn: item.sn,
              price: item.price,
              subType: item.subType,
              quantity: item.quantity,
              spec: item.spec,
              cost: item.cost,
              availableReturnQuantity: 0,
              availableShippedQuantity: 0
            };
            itemList.push(goodsDetails)
          }
        });
        let formData = {
          memberId: _this.form.memberId,
          createDate: _this.form.createDate,
          operatorId: _this.form.operatorId,
          orderMethod: _this.form.orderMethod,
          shippingMethod: _this.form.shippingMethod,
          officeId: _this.form.officeId,
          areaName: _this.form.areaName,
          address: _this.form.address,
          areaId: _this.form.areaId,
          memo: _this.form.memo,
          phone: _this.form.phone,
          consignee: _this.form.consignee,
          offsetAmount: _this.form.offsetAmount,
          itemList: itemList
        };

        calculate(formData).then(response => {

          _this.discount = response.data.order.discount
          _this.form.subPrice = response.data.amount;
          _this.form.subQuantity = response.data.order.subQuantity;
          if (!utils.isNull(response.data.order.freight)) {
            _this.form.freight = response.data.order.freight
          }
          if (!utils.isNull(response.data.order.offsetAmount)) {
            _this.form.offsetAmount = response.data.order.offsetAmount
          }
          if (!utils.isNull(response.data.order.pointDiscount)) {
            _this.form.pointDiscount = response.data.order.pointDiscount
          }
          if (!utils.isNull(response.data.order.cardDiscount)) {
            _this.form.cardDiscount = response.data.order.cardDiscount
          }
          _this.addProduct()
          _this.shippings = response.data.shippingMethods.split(',')
          _this.shippingMethod = _this.shippings[0]
          _this.form.paymentVo = response.data.order.paymentVo
          _this.form.amountPayable = response.data.amount;
          _this.amount = response.data.amount;
          _this.pay = [
            {
              amount: 0,
              chk: false,
              paymentPluginId: "cashPayPlugin",
              paymentPluginName: "现金"
            }
          ]
          _this.payAmountType = false
          _this.waitePay=response.data.amount
        }).catch(error => {

        })
      }
      ,
      //刷新商品合计
      refreshClick() {
        this.procuctFilter()
        this.calculateClick()
      }
      ,
      queryClick() {
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.query.sn);
        findBySn(params).then(response => {
          console.log(response)
          if (response.data.products.length == 1) {
            let params = new URLSearchParams()
            params.append('productId', item.id)
            params.append('memberId', this.form.memberId)
            getHistoryList(params).then(res => {
              if (res.data.length > 0) {
                var goodsDetails = {
                  productId: response.data.products[0].id,
                  name: response.data.products[0].name,
                  sn: response.data.products[0].sn,
                  cost: response.data.products[0].cost,
                  price: res.data[0].price,
                  orders: response.data.products[0].orders,
                  subTotal: res.data[0].price,
                  spec: response.data.products[0].spec1 + response.data.products[0].spec2,
                  amountPaid: 0,
                  discount: 0,
                  quantity: 1,
                  unit: response.data.products[0].unit
                };
                _this.productList.push(goodsDetails)
                _this.procuctFilter()
                _this.calculateClick()
              }else{
                var goodsDetails = {
                  productId: response.data.products[0].id,
                  name: response.data.products[0].name,
                  sn: response.data.products[0].sn,
                  cost: response.data.products[0].cost,
                  price: response.data.products[0].price,
                  orders: response.data.products[0].orders,
                  subTotal: response.data.products[0].price,
                  spec: response.data.products[0].spec1 + response.data.products[0].spec2,
                  amountPaid: 0,
                  discount: 0,
                  quantity: 1,
                  unit: response.data.products[0].unit
                };
                _this.productList.push(goodsDetails)
                _this.procuctFilter()
                _this.calculateClick()
              }
            })

          } else if (response.data.products.length > 1) {
            _this.findByList = response.data.products
            _this.queryType = true
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      queryClose() {
        this.queryType = false
      }
      ,
      findByClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          _this.productList.push(item)
        });
        this.queryType = false
        this.procuctFilter();
        this.calculateClick()
      }
      ,
      toCalculateClick() {
        var _this = this;
        if (_this.form.offsetAmount == '' || _this.form.offsetAmount < 0) {
          _this.form.offsetAmount = 0
        }
        if (_this.form.offsetAmount > _this.form.amountPayable) {
          _this.form.offsetAmount = _this.form.amountPayable
        }
        _this.calculateClick()
      }
      ,
      chooseClick(index, chk) {
        var _this = this
        var pay = [
          {
            amount: 0,
            chk: false,
            paymentPluginId: "cashPayPlugin",
            paymentPluginName: "现金"
          }
        ]
        _this.pay = pay
        _this.payAmountType = false

        if (chk == true) {
          if (_this.waitePay> 0) {
            if (_this.waitePay >= _this.form.paymentVo[index].balance) {
              _this.form.paymentVo[index].amount = _this.form.paymentVo[index].balance
              _this.waitePay=(parseFloat(_this.waitePay) - parseFloat(_this.form.paymentVo[index].balance)).toFixed(2)
              // _this.amount = (parseFloat(_this.amount) - parseFloat(_this.form.paymentVo[index].balance)).toFixed(2)
            } else {
              _this.waitePay=0
              _this.form.paymentVo[index].amount = _this.amount
              // _this.amount = 0
            }
          } else {
            _this.form.paymentVo[index].chk = false;
            _this.$message({
              message: '本商品已无法抵用优惠',
              type: 'warning'
            });
          }
          if (_this.amount > 0) {
            if (_this.amount >= _this.form.paymentVo[index].balance) {
              _this.form.paymentVo[index].amount = _this.form.paymentVo[index].balance
              // _this.waitePay=(parseFloat(_this.waitePay) - parseFloat(_this.form.paymentVo[index].balance)).toFixed(2)
              _this.amount = (parseFloat(_this.amount) - parseFloat(_this.form.paymentVo[index].balance)).toFixed(2)
            } else {
              // _this.waitePay=0
              _this.form.paymentVo[index].amount = _this.amount
              _this.amount = 0
            }
          } else {
            _this.form.paymentVo[index].chk = false;
            _this.$message({
              message: '本商品已无法抵用优惠',
              type: 'warning'
            });
          }
        } else {
          _this.waitePay=(parseFloat(_this.waitePay) + parseFloat(_this.form.paymentVo[index].amount)).toFixed(2)
          _this.amount = (parseFloat(_this.amount) + parseFloat(_this.form.paymentVo[index].amount)).toFixed(2)
          _this.form.paymentVo[index].amount = 0
        }
      }
      ,
      addPayClick(index) {
        var _this = this
        if (_this.pay[index].paymentPluginId != '') {
          var pay = {
            amount: 0,
            chk: false,
            paymentPluginId: "cashPayPlugin",
            paymentPluginName: "现金"
          };
          _this.pay.push(pay)
        } else {
          _this.$message({
            message: '请先选择选项',
            type: 'warning'
          });
        }
      }
      ,
      delClick(index) {
        var _this = this;
        var amount = 0
        _this.pay.splice(index, 1)
        _this.payAmountType = false
        _this.pay.forEach(function (item, indexs) {
          amount += parseFloat(item.amount)
        })
        this.waitePay=Number(this.amount).toFixed(2)-Number(amount).toFixed(2)
        this.waitePay=Number(this.waitePay).toFixed(2)
      }
      ,
      inputClick(index) {
        var _this = this
        if (Number(_this.pay[index].amount) == '' || Number(_this.pay[index].amount) < 0) {
          _this.pay[index].amount = 0
        }
        console.log(_this.pay)
        var amount = 0
        var price = 0
        _this.pay.forEach(function (item, indexs) {
          amount += parseFloat(item.amount)
          if (index != indexs) {
            price += parseFloat(item.amount)
          }
        })
        if (Number(_this.pay[index].amount) > (Number(_this.amount) - Number(price))) {
          _this.pay[index].amount = (Number(_this.amount) - Number(price)).toFixed(2)
          _this.waitePay=Number(_this.waitePay).toFixed(2) - Number( _this.pay[index].amount).toFixed(2)
          console.log(_this.pay)
          this.waitePay=Number(this.waitePay).toFixed(2)
        }else {
          _this.waitePay=Number(_this.amount).toFixed(2) - Number(amount).toFixed(2)
          this.waitePay=Number(this.waitePay).toFixed(2)
        }
        if (amount >= _this.amount) {
          _this.payAmountType = true
        } else {
          _this.payAmountType = false
        }
        // else {
        //   var paymentVo = _this.form.paymentVo.concat(_this.pay);
        //   var amount = 0
        //   paymentVo.forEach(function (item) {
        //     amount += parseFloat(item.amount)
        //   });
        //   console.log(amount)
        //   _this.amount = (parseFloat(_this.form.amountPayable) - parseFloat(amount)).toFixed(2)
        // }
      },

      loadReceiver() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 100);
        params.append('memberId', _this.form.memberId);
        receiverList(params).then(response => {
          console.log(response)
          // _this.loadMapLine(response.data.data[0].id)
          _this.receiverForm = response.data.data
          _this.form.receiverId = response.data.data[0].id
          _this.form.address = response.data.data[0].address
          _this.form.areaName = response.data.data[0].areaName
          _this.form.areaId = response.data.data[0].areaId;
          _this.form.consignee = response.data.data[0].consignee;
          _this.form.phone = response.data.data[0].phone
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectReceiver(data) {
        console.log(data)
        var _this = this
        if (utils.isNull(_this.form.memberId)) {
          _this.$message({
            message: '请先选择客户',
            type: 'warning'
          });
          this.form.address = ''
          return;
        }
        if (data == '#') {
          _this.receiverVisible = true;
          this.times = new Date().getSeconds()
          this.form.address = ''
        } else {
          // _this.loadMapLine(data.id)
          _this.form.receiverId=data.id
          _this.form.address = data.address
          _this.form.areaName = data.areaName
          _this.form.areaId = data.areaId;
          _this.form.consignee = data.consignee;
          _this.form.phone = data.phone
        }
      },
      receiverClose() {
        this.receiverVisible = false;
      },
      orderReceiver(data) {
        var _this = this;
        _this.receiverForm.push(data.data)
        _this.form.address = data.data.address
        _this.form.areaName = data.data.areaName
        _this.form.areaId = data.data.areaId;
        _this.form.consignee = data.data.consignee;
        _this.form.phone = data.data.phone;
        _this.receiverClose()
      },
      resetClick() {
        this.form = {
          memberId: '',
          taxType: '0',
          receiverId: '',
          shopId: '',
          orderDate: new Date(),
          operatorId: '',
          // property: 0,
          orderMethod: '1',
          shippingMethod: '',
          officeId: '',
          areaId: null,
          areaName: '',
          address: '',
          memo: '',
          consignee: '',
          phone: '',
          freight: 0,
          amountPayable: 0,
          amountPaid: 0,
          paymentMethod: '0',
          subPrice: 0,
          subQuantity: 0,
          offsetAmount: 0,
          pointDiscount: 0,
          cardDiscount: 0,
          paymentVo: []
        }
        this.pay= [
          {
            amount: 0,
            chk: false,
            paymentPluginId: "cashPayPlugin",
            paymentPluginName: "现金"
          }
        ],
        this.productList = []
        this.discount = 0
        this.amount = 0
      }
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }
  .options{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    position: absolute;
    bottom:13%;
    width: 100%
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    width: 25%;
    height: 40px
  }
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
